<template>
    <div>
        <el-form :inline="true" ref="form" :model="form" label-width="66px" class="demo-form-inline">
            <el-form-item label="搜索:" prop="title">
                <el-input size="mini" placeholder="请输入名称" v-model="form.title"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="search" size="mini">搜索</el-button>
            </el-form-item>
            <el-form-item class="backbtn1">
                <BackBtn type="primary" size="mini" @click="$router.go(-1)">返回</BackBtn>
            </el-form-item>

        </el-form>
        <el-row>
            <div class="btnlist">


                <div class="btnlist__item">
                    <pers-button type="danger" @click="batchDel" size="mini" label="批量删除"
                        perms="kanke:textbook:classcourse:batch-del"></pers-button>

                </div>
                <div class="btnlist__item">
                    <pers-button @click="handleSort" size="mini" :label="showSort ? '取消排序' : '排序'"
                        perms="kanke:textbook:classcourse:sort"></pers-button>

                </div>
                <div class="btnlist__item">
                    <pers-button type="primary" @click="addFolder" size="mini" label="新建文件夹"
                        perms="kanke:textbook:classcourse:add-folder"></pers-button>

                </div>
                <div class="btnlist__item">
                    <pers-button type="primary" @click="addCourse" size="mini" label="添加"
                        perms="kanke:textbook:classcourse:add"></pers-button>

                </div>
            </div>
        </el-row>
        <el-row v-loading="loading">
            <div v-if="showSelect" class="head">
                <el-button type="primary" @click="handleConfirmDel(true)" size="mini">确定</el-button>
                <el-button @click="handleCloseSelect" size="mini">取消</el-button>
                <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选 (已选
                    {{
                        checkList.length }} 条)</el-checkbox>
                <span> <span style="color: red">*</span> 文件夹类型暂不支持批量删除</span>
            </div>
            <el-checkbox-group v-model="checkList" @change="handleCheckedCitiesChange">
                <div class="content" v-if="tableData.length">
                    <div class="content__item" v-for="(item, index) in tableData"
                        :key="`${item.type}-${item.id}-${index}`">
                        <el-checkbox v-if="showSelect && item.book_type != 5" :label="item.id"></el-checkbox>
                        <el-tag effect="dark" size="small" :type="getType(item)">{{ getItemTag(item)
                            }}</el-tag>
                        <el-image style="width: 150px; height: 150px" :src="item.cover_url" :fit="fit"
                            @click="handleClick($event, item)"></el-image>
                        <span class="title">{{ item.title }}</span>
                        <el-button v-if="showSort" type="primary" size="small" @click="handleSortItem(item)">排序-{{
                            item.sort_num }}</el-button>
                        <pers-button v-else size="small" icon="el-icon-delete" @click="handleDelItem(item)"
                            perms="kanke:textbook:classcourse:del"></pers-button>

                    </div>
                </div>
                <el-empty v-else description="暂无数据"></el-empty>
            </el-checkbox-group>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="pageInfo.pageNumber" :page-sizes="pageSizes" :page-size="pageInfo.pageSize" background
                layout="total, sizes, prev, pager, next, jumper" :total="pageInfo.total">
            </el-pagination>
            <AddFolder :dialogVisible.sync="dialogVisible" @handleConfirm="handleConfirm" :type="type" />
            <!-- 显示通用素材上传 调用基础素材 -->
            <!-- <show-add-course-ware v-if="uploadDialogVisible" :visible.sync="uploadDialogVisible" :task_type="task_type"
                :select_type="type" @handleSelectFiles="handleSelectFiles"
                :edit_task_courseware_arr="edit_task_courseware_arr" /> -->
            <SelectMaterial v-if="uploadDialogVisible" :visible.sync="uploadDialogVisible"
                @handleSelectFiles="handleSelectFiles" :edit_task_courseware_arr="edit_task_courseware_arr"
                :select_type="select_type" />
        </el-row>
    </div>
</template>
<script>
import { getList, sortFolder, deleteCourse, deleteFolder, addCourse } from "@/api/kanke/textbook/classcourse";
import { pageSizes } from '@/constant/index';
import { COURSEWARE_TYPE_MAP, COURSEWARE_TYPE_COLOR_MAP } from '@/constant/kanke/courseware';
import AddFolder from './AddFolder.vue'
import ShowAddCourseWare from "@/views/kanke/textbook/courseware/components/ShowAddCourseWare.vue";
import { getPageSize } from '@/utils';
import PersButton from '../../../../../components/PersButton.vue';
import SelectMaterial from "../../components/SelectMaterial.vue";

export default {
    name: "KanKeTextbookClassCourseTabPane",
    props: {
        type: {
            type: String,
            default: 'book'
        }
    },
    components: {
        AddFolder,
        ShowAddCourseWare,
        PersButton,
        SelectMaterial
    },
    data() {
        return {
            task_type: -1,// 4可以选所有
            loading: false,
            image: 'image',
            form: {
                title: ''
            },
            pageInfo: {
                pageSize: 10,
                pageNumber: 1,
                total: 0
            },
            tableData: [],
            fit: 'contain',
            pageSizes,
            courseModal: false,
            folderModal: false,
            checkList: [],
            isIndeterminate: true,
            checkAll: false,
            showSelect: false,
            showSort: false,
            dialogVisible: false,
            uploadDialogVisible: false,
            edit_task_courseware_arr: [],
            select_type: []
        }
    },
    created() {
        this.pageInfo.pageSize = getPageSize() || 12
        this.init();
    },
    computed: {
        class_id() {
            return this.$route.query.class_id
        },
        folder_id() {
            return this.$route.query.folder_id
        }
    },
    methods: {
        init() {

            this.loading = true;

            const params = {
                ...this.form,
                ...this.pageInfo,
                class_id: this.class_id,
                folder_id: this.folder_id,
                type: this.type
            };

            getList(params).then((res) => {
                this.tableData = res.data.list;
                this.pageInfo.total = res.data.total;
                this.loading = false;
            })
        },
        handleChildFileEvent() {

        },
        handleSelectFiles(files) {
            if (files.length == 0) {
                this.$message.error('请选择要上传的文件')
                return;
            }
            let allow_type = [1, 2, 3, 4]
            if (this.$route.query.type == 'book') {
                allow_type = [1]
            }
            if (this.$route.query.type == 'other') {
                allow_type = [2, 3, 4]
            }
            let checkRes = true;
            files.map(item => {
                if (!allow_type.includes(item.book_type)) {
                    checkRes = false
                }
            })
            if (!checkRes) {
                this.$message.error('请选择正确的课件类型!')
                return
            }
            const courseIdArr = files.map(item => item.id)
            const params = {
                class_id: this.class_id,
                folder_id: this.folder_id,
                courseIdArr
            }
            addCourse(params).then(res => {
                if (res.code == 200) {
                    this.$message.success(res.msg)
                    this.init()
                }
            })

        },
        handleConfirm() {
            this.dialogVisible = false
            this.init()
        },
        addCourse() {
            this.uploadDialogVisible = true
            this.select_type = this.type == 'book' ? [1] : [2, 3, 4]
        },
        handleDelItem(item) {
            if (item.book_type != 5) {
                this.handleConfirmDel(false, item.id)
                return;
            }
            this.$confirm('确定要删除吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(() => {
                const params = {
                    id: item.id
                }
                deleteFolder(params).then(res => {
                    if (res.code == 200) {
                        this.$message.success(res.msg)
                        this.init()
                    }
                })
            })

        },
        handleConfirmDel(isBatch = false, id = 0) {
            const delArr = isBatch ? this.checkList : [id]
            if (delArr.length == 0) {
                this.$message.warning('请选择要删除的课件')
                return;
            }
            this.$confirm('确定要删除吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(() => {
                const params = {
                    courseIdArr: [...delArr],
                    folder_id: this.folder_id,
                    class_id: this.class_id
                }
                deleteCourse(params).then(res => {
                    if (res.code == 200) {
                        this.$message.success(res.msg)
                        this.init()
                    }
                })
            })

        },
        addFolder() {
            this.dialogVisible = true;
        },
        handleSort() {
            this.showSelect = false
            this.showSort = !this.showSort
        },
        handleSortItem(item) {

            this.$prompt('请输入新的序号', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputValue: item.sort,
                inputPattern: /\d+/,
                inputErrorMessage: '序号不合法,仅支持数字'
            }).then(({ value }) => {
                const params = {
                    book_type: item.book_type,
                    sort_num: value,
                    id: item.id,
                    folder_id: this.folder_id,
                    class_id: this.class_id
                }
                sortFolder(params).then(res => {
                    if (res.code == 200) {
                        this.$message.success(res.msg)
                        this.init()
                    }
                })
            })

        },
        batchDel() {
            this.showSort = false
            this.showSelect = true
        },
        handleCloseSelect() {
            this.showSelect = false
        },
        handleCheckAllChange(val) {
            const checkList = this.tableData.map(item => item.id);
            this.checkList = val ? checkList : [];
            this.isIndeterminate = false;
        },
        handleCheckedCitiesChange(value) {
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.tableData.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.tableData.length;
        },
        getType({ book_type }) {
            return COURSEWARE_TYPE_COLOR_MAP[book_type] || '未知'
        },
        getItemTag({ book_type }) {
            return COURSEWARE_TYPE_MAP[book_type] || '未知'
        },
        search() {
            this.init()
        },
        handleSizeChange: function (e) {
            this.pageInfo.pageSize = e;
            this.init();
        },
        handleCurrentChange: function (e) {
            console.log(e);
            this.pageInfo.pageNumber = e;
            this.init();
        },
        handleClick(event, item) {
            if (!event.target.matches('.el-checkbox__inner, .el-checkbox__original')) {
                // 不是checkbox或其标签，执行你的逻辑  
                // 文件夹点击可以跳转到文件夹页面
                if (item.book_type == 5) {
                    this.$router.push({
                        name: 'ClassCourse',
                        query: {
                            class_id: this.class_id,
                            folder_id: item.id,
                            type: this.type
                        }
                    })
                }
            }

        }

    }

}
</script>
<style lang="scss" scoped>
@import "@/styles/abstract/mixins.scss";

.backbtn1 {
    float: right;
}

.btnlist {

    padding: 5px 20px;

    &__item {
        margin-right: 25px;
        float: right;
    }

}

.head {
    padding: 5px 20px;

    :nth-child(2) {
        margin-right: 20px;
    }

}

.content {
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    justify-content: flex-start;
    margin-bottom: 15px;
    min-height: 700px;

    &__item {
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        margin: 20px;
        padding: 15px 10px;
        border: 1px solid #ccc;
        border-radius: 5px;
        font-size: 14px;

        ::v-deep .el-checkbox__label {
            display: none;
        }

        ::v-deep .el-checkbox {
            font-size: 11px;
        }


        .el-tag {
            position: absolute;
            top: 0;
            left: 0;
            z-index: 10;

        }

        .title {
            width: 140px;
            max-height: 48px;
            line-height: 16px;
            margin: 10px 0;
            word-break: break-word;
            white-space: normal;
            @include line-clamp(3);
        }

        .el-button {
            width: 100%;

        }

        .el-checkbox {
            position: absolute;
            top: 0;
            right: 0;
        }
    }
}
</style>